package com.xin.components.base
{
	import flash.events.MouseEvent;
	
	public class RadioButtonBase extends LiteSprite
	{
		private static var _buttons:Array = [];
		
		protected var _selected:Boolean = false;
		protected var _groupName:String;
		
		public function RadioButtonBase(w:int, h:int, groupName:String, selected:Boolean = false, defaultHandler:Function = null)
		{
			RadioButtonBase.addButton(this, groupName);
			
			_selected = selected;
			_groupName = groupName;
			
			if (defaultHandler != null)
			{
				addEventListener(MouseEvent.CLICK, defaultHandler);
			}
			
			super(w, h);
		}
		
		/**
		 * 静态方法, 添加RadioButton
		 */		
		private static function addButton(radioButton:RadioButtonBase, groupName:String):void
		{
			if (_buttons[groupName] == null)
				_buttons[groupName] = []; 
				
			_buttons[groupName].push(radioButton);
		}
		
		/**
		 * 静态方法, 将指定RadioButton之外的所有与之同组的RadioButton设为不选择状态
		 */		
		private static function clear(radioButton:RadioButtonBase):void
		{
			var radios:Array = _buttons[radioButton.groupName];
			if (radios == null) return;
			
			for each (var item:RadioButtonBase in radios)
			{
				if (item != radioButton)
				{
					item.selected = false;
				}
			}
		}
		
		protected override function init():void
		{
			super.init();
			
			mouseChildren = false;
			buttonMode = useHandCursor = true;
			
			//优先级高于 defaultHandler
			addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void
			{
				selected = true;
			}, false, 1);
			
			selected = _selected;
		}
		
		/**
		 * 切换到选择状态
		 */		
		protected function goSelect():void{};
		
		/**
		 * 切换到非选择状态
		 */		
		protected function goUnselect():void{};
		
		/////////////////////////////////////////////
		// 公开方法
		/////////////////////////////////////////////
		public override function draw():void
		{
			if (_selected)
			{
				goSelect();
			}
			else
			{
				goUnselect();
			}
		}
		
		/////////////////////////////////////////////
		// Getter & Setter
		/////////////////////////////////////////////
		/**
		 * 设置RadioButton所属组名称
		 */		
		public function set groupName(value:String):void
		{
			_groupName = value;
		}
		public function get groupName():String
		{
			return _groupName;
		}
		
		/**
		 * 设置是否选择
		 */		
		public function set selected(value:Boolean):void
		{
			_selected = value;
			
			if (_selected)
			{
				RadioButtonBase.clear(this);
			}
			invalidate();
		}
		public function get selected():Boolean
		{
			return _selected;
		}
	}
}